/*
 * @Description: socket心跳
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2025-04-18
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-04-28
 */

import { MessageTypeEnum } from '../enum'

/**
 * 注册登录
 * @param socket socket对象
 * @param connectState 连接状态
 * @param userId 用户id
 */
export const openRegistry = (socket: WebSocket, connectState: number, userId: string) => {
  if (connectState !== WebSocket.OPEN) return
  const msg = { type: MessageTypeEnum.REGISTER, reqMsg: 'registry', requestId: userId }
  socket.send(JSON.stringify(msg))
}

/** 心跳间隔 */
const HEARTBEAT_INTERVAL = 10 * 1000

/** 心跳定时器 */
let heartbeatTimer

/**
 * 打开心跳
 * @param socket socket对象
 * @param connectState 连接状态
 * @param userId 用户id
 */
export const openHeartbeat = (socket: WebSocket, connectState: number, userId: string) => {
  if (connectState !== WebSocket.OPEN) return
  heartbeatTimer = setInterval(() => {
    console.log('sendHeartbeat')
    const msg = { type: MessageTypeEnum.HEARTBEAT, reqMsg: 'heartbeat', requestId: userId }
    socket.send(JSON.stringify(msg))
  }, HEARTBEAT_INTERVAL)
}

/**
 * 关闭心跳
 */
export const closeHeartbeat = () => {
  console.log('closeHeartbeat')
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
    heartbeatTimer = undefined
  }
}
